package com.tange.ai.iot.client.gnssa.internal

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.os.Vibrator
import android.text.TextUtils
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.RelativeLayout
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.util.Consumer
import com.tange.ai.iot.client.gnssa.databinding.ActivityInternalQrcodeScanBinding
import com.tange.ai.iot.client.gnssa.home.HomeActivity
import com.tange.base.toolkit.*
import com.tange.base.ui.design.BasicDialogLoading
import com.tange.base.ui.design.BasicDialogRequest
import com.tange.core.access.token.Authentication
import com.tange.core.access.token.Token
import com.tange.core.backend.service.http.HttpConfigurations
import com.tange.core.data.structure.Resp
import com.tange.core.trouble.shooting.qrcode.DebuggingQrcode
import com.tg.appcommon.android.TGLog

class DebuggingQrcodeScanActivity: AppCompatActivity() {

    companion object {
        private const val TAG = "DebuggingQrcodeScanActivity_"
        private const val VIBRATE_DURATION_MILLISECONDS = 80L
        private const val RECOGNITION_INTERVAL = 1000

        private const val KEY_PKG_NAME = "package_name"
        private const val KEY_APP_ID = "app_id"
        private const val KEY_ACCESS_TOKEN = "access_token"

        const val PRE_DEBUGGING_CODE = "PRE_DEBUGGING_CODE"
    }

    private lateinit var binding: ActivityInternalQrcodeScanBinding

    private var recentlyRecognizedMoment = 0L

    private var loading: BasicDialogLoading? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        StatusBarUtil.setLightStatusBar(this, true)
        StatusNavUtils.setTranslucentStatus(this)
        super.onCreate(savedInstanceState)

        binding = ActivityInternalQrcodeScanBinding.inflate(layoutInflater).apply {
            setContentView(root)
            supportActionBar?.hide()
            top.left.onClicked { finish() }
        }

        (binding.top.layoutParams as RelativeLayout.LayoutParams).apply {
            topMargin = DisplayUtils.statusBarHeight(this@DebuggingQrcodeScanActivity)
            binding.top.layoutParams = this
        }

        window.apply {
            var uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            uiFlags = uiFlags or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            statusBarColor = Color.TRANSPARENT
            decorView.systemUiVisibility = uiFlags
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            }
        }

        binding.qrCodeScan.setOnQrCodeScanListener { result -> onQrcodeRecognized(result) }

        val last = PreferenceUtil.getString(this@DebuggingQrcodeScanActivity, PRE_DEBUGGING_CODE, "")
        if (!TextUtils.isEmpty(last)) {
            BasicDialogRequest(this@DebuggingQrcodeScanActivity).apply {
                setMessage("要使用上一次的调试码？")
                setPositiveText("好的")
                setPositiveOnClicked {
                    dismiss()
                    onQrcodeRecognized(last)
                }
                setNegativeText("算了")
                setNegativeOnClicked {
                    dismiss()
                }
            }.show()
        }
    }

    private fun configure(packageName: String, appId: String, accessToken: String, consumer: Consumer<Resp<Token?>>) {
        HttpConfigurations.getInstance().appId = appId
        HttpConfigurations.getInstance().setPackageName(packageName)
        Authentication.configure(accessToken, consumer)
    }

    private fun onQrcodeRecognized(result: String?) {
        TGLog.i(TAG, "[onQrcodeRecognized] $result")
        if (now() - recentlyRecognizedMoment <= RECOGNITION_INTERVAL) return
        recentlyRecognizedMoment = now()
        (getSystemService(Context.VIBRATOR_SERVICE) as Vibrator).vibrate(VIBRATE_DURATION_MILLISECONDS)

        if (loading?.isShowing == true) {
            loading?.dismiss()
        }

        loading = BasicDialogLoading(this).apply {
            setMessage("数据解析中...")
        }
        loading?.show()

        DebuggingQrcode.parse(result) {
            if (it.success) {
                applyAccessToken(it.data!!, result!!)
            } else {
                ui { loading?.dismiss() }
                ui { Tips.show("Error: ${it.message}") }
            }
        }
    }

    private fun applyAccessToken(token: String, qrCodeContent: String) {
        Authentication.configure(token) {
            ui { loading?.dismiss() }
            if (it.success && it.data != null) {
                PreferenceUtil.setString(this@DebuggingQrcodeScanActivity, PRE_DEBUGGING_CODE, qrCodeContent)
                startActivity(Intent(this, HomeActivity::class.java).apply {
                    putExtra(HomeActivity.PARAM_DEBUGGING_MODE, true)
                })
                finish()
            } else {
                ui { loading?.dismiss() }
                PreferenceUtil.setString(this@DebuggingQrcodeScanActivity, PRE_DEBUGGING_CODE, "")
                Toast.makeText(this, "校验失败: ${it.message}", Toast.LENGTH_LONG).show()
                finish()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        binding.qrCodeScan.onStart()
    }

    override fun onPause() {
        super.onPause()
        binding.qrCodeScan.onStop()
    }

    override fun onDestroy() {
        super.onDestroy()
        ui {
            loading?.dismiss()
        }
        binding.qrCodeScan.onDestroy()
    }
}